﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataBaseFactoryLib;

namespace SQLToolsCore
{
    public partial class Login : Form
    {
        private string uidVal = string.Empty, pwdVal = string.Empty;
        private readonly List<ConnectionHistory> _historyLst = ConnectHistoryOpr.GetConnectionHistory();
        private readonly DataBaseFactory dbFactory = new DataBaseFactory();

        public Login()
        {
            InitializeComponent();
            if (_historyLst != null && _historyLst.Count > 0)
            {
                dataBaseType.SelectedIndex = _historyLst.First().DataBaseType;

                server.DataSource = _historyLst.Where(x => x.DataBaseType == dataBaseType.SelectedIndex)?.Select(x => x.Server).ToArray();
                server.SelectedIndex = 0;
            }
            else
            {
                dataBaseType.SelectedIndex = 0;
            }

            if (dataBaseType.SelectedIndex == 0)
            {
                dbFactory.SetDataBaseType(DataBaseTypeEnum.MSSQL);
            }
            else
            {
                dbFactory.SetDataBaseType(DataBaseTypeEnum.MYSQL);
            }
        }

        //窗体加载完成时，设置端口输入框是否可见
        private void Login_Shown(object sender, System.EventArgs e)
        {
            if (dataBaseType.SelectedIndex != 0)
            {
                connType.Visible = false;
                label4.Visible = false;
            }
            else
            {
                PortLabel.Visible = false;
                PortValue.Visible = false;
            }
        }

        //MSSQL数据库登录验证形式
        private void MSSQLConnectionTypeChanged(object sender, EventArgs e)
        {
            if (connType.SelectedIndex == 0)
            {
                if (!string.IsNullOrEmpty(uidVal))
                {
                    uid.Text = uidVal;
                }
                if (!string.IsNullOrEmpty(pwdVal))
                {
                    pwd.Text = pwdVal;
                }
                uid.Enabled = true;
                pwd.Enabled = true;
            }
            else
            {
                if (!string.IsNullOrEmpty(uid.Text))
                {
                    uidVal = uid.Text;
                }
                if (!string.IsNullOrEmpty(pwd.Text))
                {
                    pwdVal = pwd.Text;
                }

                uid.Enabled = false;
                pwd.Enabled = false;

                uid.Text = string.Empty;
                pwd.Text = string.Empty;
            }
        }

        //根据历史数据初始化值
        private void InitValueByCon()
        {
            var defaultInfo = _historyLst.FirstOrDefault(x => x.DataBaseType == dataBaseType.SelectedIndex && x.Server == server.Text);

            if (defaultInfo == null)
            {
                connType.SelectedIndex = 1;
                PortValue.Text = string.Empty;
                uidVal = string.Empty;
                pwdVal = string.Empty;
            }
            else
            {
                connType.SelectedIndex = defaultInfo.ConnType ? 1 : 0;
                PortValue.Text = defaultInfo.Port.ToString();
                uid.Text = defaultInfo.Uid;
                pwd.Text = defaultInfo.Password;
            }
        }
        //server记录选择切换
        private void HistoryServerRecordChanged(object sender, EventArgs e)
        {
            InitValueByCon();
        }

        //重新输入server_text时重置账号密码
        private void ReInputServerInfo(object sender, EventArgs e)
        {
            if (connType.SelectedIndex == 0)
            {
                uidVal = string.Empty;
                pwdVal = string.Empty;
                uid.Text = string.Empty;
                pwd.Text = string.Empty;
            }
        }

        //版本查看
        private void ShowVersionInfo(object sender, EventArgs e)
        {
            new TemplateEditer(1000, 600,
                CommonTools.LoadContent(AppDomain.CurrentDomain.BaseDirectory + @"resrc\update_log.log", Encoding.UTF8), "更新日志").Show();
        }

        //切换端口输入框显示
        private void SwitchPortTextBoxVisible()
        {

            if (dataBaseType.SelectedIndex == 0)
            {
                dbFactory.SetDataBaseType(DataBaseTypeEnum.MSSQL);
                if (connType.SelectedIndex == 1)
                {
                    uid.Enabled = false;
                    pwd.Enabled = false;
                }
                PortLabel.Visible = false;
                PortValue.Visible = false;
                connType.Visible = true;
                label4.Visible = true;
            }
            else
            {
                dbFactory.SetDataBaseType(DataBaseTypeEnum.MYSQL);
                uid.Enabled = true;
                pwd.Enabled = true;
                PortLabel.Visible = true;
                PortValue.Visible = true;
                connType.Visible = false;
                label4.Visible = false;
            }
        }
        //切换数据库类型
        private void DataBaseTypeChanged(object sender, EventArgs e)
        {
            server.DataSource = _historyLst.Where(x => x.DataBaseType == dataBaseType.SelectedIndex)?.Select(x => x.Server).ToArray();
            if (server.DataSource != null && ((string[])server.DataSource).Length > 0)
                server.SelectedIndex = 0;
            else
                server.Text = string.Empty;
            InitValueByCon();
            SwitchPortTextBoxVisible();
        }


        //获取该服务下所有数据库
        private List<string> GetDBNameList()
        {
            var rtnLst = new List<string>();
            string sqlStr;
            var dbOpr = DBHelper.GetInstanse(dbFactory);
            switch (dbOpr.DbType)
            {
                case DataBaseTypeEnum.MYSQL:
                    dbOpr.SetBaseParam(server.Text, Convert.ToInt32(PortValue.Text), uid.Text, pwd.Text);
                    dbOpr.SetDataBaseName("information_schema");

                    sqlStr = @"SELECT SCHEMA_NAME AS `name` FROM INFORMATION_SCHEMA.SCHEMATA
                    where SCHEMA_NAME not in ('mysql','information_schema','performance_schema','sys');";
                    break;
                case DataBaseTypeEnum.MSSQL:
                default:
                    if (connType.SelectedIndex == 0)
                    {
                        dbOpr.SetBaseParam(server.Text, Convert.ToInt32(PortValue.Text), uid.Text, pwd.Text);
                        dbOpr.SetDataBaseName("master");
                    }
                    else
                    {
                        dbOpr.SetBaseParam(server.Text, 0, "", "");
                        dbOpr.SetDataBaseName("master");
                    }
                    sqlStr = @"select name from master..sysdatabases
                    where name not in ('master','model','msdb','tempdb')";
                    break;
            }

            var dt = dbOpr.QueryDataTable(sqlStr);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    rtnLst.Add(dr[0].ToString());
                }
            }
            SaveLoginHistory();

            return rtnLst;
        }
        //记录登录历史
        private void SaveLoginHistory()
        {
            var connectionHistory = _historyLst.FirstOrDefault(x => x.DataBaseType == dataBaseType.SelectedIndex && x.Server == server.Text);
            if (connectionHistory == null)
            {
                //添加到list中，若list数量超过5条删除最后一条
                if (_historyLst.Count > 4)
                {
                    _historyLst.RemoveAt(_historyLst.Count - 1);
                }
            }
            else
            {
                //修改
                _historyLst.Remove(connectionHistory);
            }
            //新增
            connectionHistory = new ConnectionHistory()
            {
                DataBaseType = dataBaseType.SelectedIndex,
                Port = string.IsNullOrWhiteSpace(PortValue.Text) ? 0 : Convert.ToInt32(PortValue.Text),
                Server = server.Text,
                ConnType = dataBaseType.SelectedIndex == 0 && connType.SelectedIndex != 0,
                Uid = uid.Text,
                Password = pwd.Text
            };
            _historyLst.Insert(0, connectionHistory);

            ConnectHistoryOpr.SaveConnectionHistory(_historyLst);
        }
        //SQL脚本执行器窗口
        private void ShowExecuter(object sender, EventArgs e)
        {
            try
            {
                var DBNameList = GetDBNameList();

                Executer form2 = new(DBNameList, this);
                form2.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //数据库各对象操作窗口
        private void ShowController(object sender, EventArgs e)
        {
            try
            {
                var DBNameList = GetDBNameList();
                Controller form3 = new(DBNameList, this);
                form3.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}
